<template>
  <div class="editor-wrapper">
    <div id="editor" />
  </div>
</template>

<script>
import WangEditor from 'wangeditor'

export default {
  props: {
    value: {
      props: {
        type: String,
        default: ''
      }
    }
  },
  data() {
    return {
      instance: null
    }
  },
  watch: {
    value() {
      if (this.instance.txt.html() === this.value) {
        return
      }
      this.instance.txt.html(this.value)
    }
  },
  mounted() {
    this.instance = new WangEditor(document.getElementById('editor'))
    Object.assign(this.instance.config, {
      uploadImgServer:
        'https://admin.xmzhuchen.com/api/base/upload?phone=17750621301',
      uploadFileName: 'file',
      onchange: () => {
        this.$emit('input', this.instance.txt.html())
      },
      uploadImgHooks: {
        customInsert: (insertImgFn, result) => {
          insertImgFn('https://admin.xmzhuchen.com/' + result.data.file.url)
        },
        error() {}
      }
    })

    this.instance.create()
    this.instance.txt.html(this.value)
  },
  beforeDestroy() {
    this.instance.destroy()
    this.instance = null
  }
}
</script>

<style>
.editor-wrapper {
  position: relative;
  z-index: 10;
}
</style>
